package com.hmdp.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * @Author LA
 * @Date 2024/8/12 15:23
 * @Description: 全局拦截，用于刷新token
 * springMVC中提供的拦截器
 * 实现了三种类型拦截器：preHandle(..)、postHandle(..)、afterCompletion(..)
 * Handler指的其实就是controller
 */
@Slf4j
@Component
public class RefreshTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //返回值为true则放行这个请求   为false则终止
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.warn("全局前置token刷新拦截器........preHandle.......");
        //1.获取请求头中的token
        String token = request.getHeader("authorization"); //authorization是前端里面设置的
            //判断token是否为空
        if (StrUtil.isBlank(token)) {
            //为空，直接放行
            return true;
        }
        //2.基于token获取redis中的用户
        Map<Object, Object> userHash = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY+token);
        //3.判断用户是否存在
        if (MapUtil.isEmpty(userHash)) {
            return true;
        }
        //5.将redis中获取的hash类型的数据转换为UserDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userHash, new UserDTO(), false);
        //6.存在，保存用户信息到ThreadLocal(此处我们选择使用我们提前创建过的ThreadLocal工具类)
        UserHolder.saveUser(userDTO);
        //7.刷新token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.warn("身份校验拦截器---afterCompletion..............");
        //清理线程池
        UserHolder.removeUser();
    }
}









